package Thread;

/**
 * @author 逸尘风清
 * @date 2021/4/28
 * @time 13:55
 * 描述：
 */

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁（共享锁和排他锁（互斥锁））
 */
public class ReadAndWriteLock2 {
    private static Lock lock = new ReentrantLock();   // 定义排它锁
    private static int value;

    static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    static Lock readLock = readWriteLock.readLock();
    static Lock writeLock = readWriteLock.writeLock();

    public static void read(Lock lock){
        try {
            lock.lock();
            Thread.sleep(1000);
            System.out.println("read over");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static void write(Lock lock, int v){
        try {
            lock.lock();
            Thread.sleep(1000);
            value = v;
            System.out.println("write over");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        Runnable readR = ()-> read(readLock);
        Runnable writeR = ()-> write(writeLock,5);
        for (int i = 1; i <= 18; i++) {
            new Thread(readR).start();
        }
        for (int i = 1; i <= 2; i++) {
            new Thread(writeR).start();
        }
    }
    /**
     * 以上程序运行结果： 读的线程使用共享锁，可以瞬间完成所有的读操作。
     */
}
